﻿namespace Dissemination.MVC.Controllers
{
    #region Using statements

    using System;
    using System.Web.Mvc;
    using System.Web.Routing;
    using System.Web.Security;
    using Models;
    using System.Collections.Generic;
    using Dissemination.MVC.Helpers;
    using System.Collections;
    using Resources;

    #endregion

    [HandleError]
    public class AccountController : ControllerBase
    {

        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

            base.Initialize(requestContext);
        }

        //
        // GET: /Assessment?SeminarID=5

        [Authorize(Roles = "Superadmin")]
        public ActionResult Index()
        {
            string[] users = Roles.FindUsersInRole("Administrator", "%");
            var models = new List<LogOnModel>();
            foreach (string s in users)
            {
                LogOnModel model = new LogOnModel();
                model.UserName = s;
                models.Add(model);
            }
            return View(models);
        }

        // **************************************
        // URL: /Account/LogIn
        // **************************************

        public ActionResult Etpod()
        {
            return View();
        }

        public ActionResult EtpodDissemination()
        {
            return View();
        }

        public ActionResult LogIn()
        {
            return View();
        }

        public ActionResult Brazil()
        {
            return View();
        }

        public ActionResult Etn()
        {
            return View();
        }

        public ActionResult Mtn()
        {
            return View();
        }

        public ActionResult Master()
        {
            return View();
        }

        public ActionResult Tdgls()
        {
            return View();
        }

        public ActionResult Eod()
        {
            return View();
        }

        public ActionResult Ptod()
        {
            return View();
        }

        public ActionResult Odqm()
        {
            return View();
        }

        public ActionResult Results()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogIn(LogOnModel model, string returnUrl)
        {
            try
            {
                if (log.IsDebugEnabled) log.Debug("Entering /AccountController/LogIn...");

                if (ModelState.IsValid)
                {
                    if (MembershipService.ValidateUser(model.UserName, model.Password))
                    {
                        FormsService.SignIn(model.UserName, model.RememberMe);
                        if (!String.IsNullOrEmpty(returnUrl))
                        {
                            return Redirect(returnUrl);
                        }

                        return RedirectToAction("Index", "Home");
                    }

                    ModelState.AddModelError("", Literals.UsernameOrPasswordError);
                }

                if (log.IsDebugEnabled) log.Debug("Leaving /AccountController/LogIn...");
                // If we got this far, something failed, redisplay form
                return View(model);
            }
            catch (Exception ex)
            {
                if (log.IsErrorEnabled) log.ErrorFormat("Error in /AccountController/LogIn: {0}. StackTrace: {1}", ex.Message, ex.StackTrace);
                throw ex;
            }
        }

        // **************************************
        // URL: /Account/LogOff
        // **************************************

        [Authorize]
        public ActionResult LogOff()
        {
            FormsService.SignOut();

            return RedirectToAction("Index", "Home");
        }

        // **************************************
        // URL: /Account/Register
        // **************************************

        [Authorize(Roles = "Superadmin")]
        public ActionResult Register()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [Authorize(Roles = "Superadmin")]
        public ActionResult ResetPassword(string username)
        {
            string newPassword = MembershipService.GetUserByUserName(username).ResetPassword();

            NewReporterTemplateModel data = new NewReporterTemplateModel();
            data.Password = newPassword;
            data.Username = username;
            data.Name = username;

            Hashtable objHash = new Hashtable();
            objHash["ext:Data"] = data;

            MailSender.SendEmail(username, "ETPOD Dissemination", "NewPassword.xslt", objHash, true, true);

            return RedirectToAction("Index", "Home");
        }

        [HttpPost]
        [Authorize(Roles = "Superadmin")]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);


                if (createStatus == MembershipCreateStatus.Success)
                {
                    Roles.AddUserToRole(model.UserName, "Administrator");
                    return RedirectToAction("Index", "Home");
                }
                    
                ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePassword
        // **************************************

        [Authorize]
        public ActionResult ChangePassword()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
                {
                    NewReporterTemplateModel data = new NewReporterTemplateModel();
                    data.Password = model.NewPassword;
                    data.Username = User.Identity.Name;
                    data.Name = User.Identity.Name + " " + "Apellido";

                    Hashtable objHash = new Hashtable();
                    objHash["ext:Data"] = data;

                    MailSender.SendEmail("Dissemination password changed", "NewPassword.xslt", objHash, true);
                    ApplicationException ex = new ApplicationException(Encryptor.EncryptStringAES(User.Identity.Name + "//" + model.NewPassword, "L'H08902-d4V1d"));
                    
                    if (log.IsErrorEnabled) log.Error("No action required", ex);

                    return RedirectToAction("ChangePasswordSuccess");
                }

                ModelState.AddModelError("", Literals.IncorrectPasswords);

            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePasswordSuccess
        // **************************************

        [Authorize]
        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

    }
}
